import { useHistory, useLocation } from 'react-router';
import 'video-react/dist/video-react.css';
import HistoryIcon from '@material-ui/icons/History';
import React, { useEffect, useState, useRef } from 'react';
// @ts-ignore
import { Player } from 'video-react';
import {
  Avatar,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  ListSubheader,
  makeStyles,
} from '@material-ui/core';
import VideoCallIcon from '@material-ui/icons/VideoCall';
import { apiUrl, http } from '../../util';
import { ListItemType } from '../Home';
import { Loading } from '../../components/Loading';
import { useDirectory } from '../../context';
import qs from 'qs';
import dayjs from 'dayjs';
import { ErrorDialog } from '../../components/ErrorDialog';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    backgroundColor: theme.palette.background.paper,
  },
}));

export const PlayPage = () => {
  const classes = useStyles();
  const history = useHistory();
  const { search } = useLocation<Location>();
  const [loading, setLoading] = useState(false);
  const [listData, setListData] = useState<ListItemType[]>([]);
  const { setDirectory } = useDirectory();
  const [isError, setIsError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const { name: videoName, directory } = qs.parse(search.substring(1)) as any;
  const [videoAddress, setVideoAddress] = useState(`${apiUrl}/video${search}`);
  const playerRef = useRef();

  useEffect(() => {
    setLoading(true);
    http('list', { data: { directory } })
      .then(data => {
        setLoading(false);
        setListData(data.data);
      })
      .catch(e => {
        setLoading(false);
        setIsError(true);
        setErrorMessage(e.message);
      });
  }, [directory]);

  useEffect(() => {
    window.scrollTo(0, 0);
    setDirectory(directory.split('\\'));
    setVideoAddress(`${apiUrl}/video${search}`);
    // @ts-ignore
    playerRef.current?.load(videoAddress);
  }, [videoName, directory, videoAddress, search, setDirectory]);
  return (
    <div>
      <Player ref={playerRef}>
        <source src={videoAddress} />
      </Player>
      <List
        className={classes.root}
        subheader={
          <ListSubheader id=" Related Video">
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span>Related Videos</span>
              <span
                style={{ display: 'flex', alignItems: 'center' }}
                onClick={() => history.replace('/')}
              >
                <HistoryIcon />
              </span>
            </div>
          </ListSubheader>
        }
      >
        <Loading loading={loading} />
        {listData
          .filter(item => item.type === 'VIDEO')
          .map((video, index) => (
            <ListItem
              key={video.name + index}
              button
              onClick={e => history.push(`/video?${qs.stringify({ directory, name: video.name })}`)}
            >
              <ListItemAvatar>
                <Avatar style={{ color: '#f55385', backgroundColor: 'white' }}>
                  <VideoCallIcon fontSize="large" />
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={video.name}
                secondary={`${
                  video.size / 1024 / 1024 < 1024
                    ? (video.size / 1024 / 1024).toFixed(2) + 'MB'
                    : (video.size / 1024 / 1024 / 1024).toFixed(2) + 'GB'
                } | ${dayjs(video.lastModified).format('YYYY年MM月DD日 HH:mm:ss')}`}
              />
            </ListItem>
          ))}
      </List>
      <ErrorDialog isError={isError} setIsError={setIsError} message={errorMessage} />
    </div>
  );
};
